package org.niu.tree;

import java.util.LinkedList;
import java.util.Queue;

public class IsBalanced {
    boolean flag = true;
    public boolean IsBalanced_Solution(TreeNode root) {
        IsBalanced(root);
        return flag;
    }
    void IsBalanced(TreeNode root){
        if(root == null) return;
        int h1 = getHeight(root.left);
        int h2 = getHeight(root.right);
        if(Math.abs(h1-h2) > 1){
            flag = false;
        }
        IsBalanced_Solution(root.left);
        IsBalanced_Solution(root.right);
    }
    int getHeight(TreeNode root){
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int h = 0;
        while (!q.isEmpty()){
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = q.poll();
                if(poll!=null&&poll.left != null) q.add(poll.left);
                if(poll!=null&&poll.right !=null) q.add(poll.right);
            }
            h++;
        }
        return h;
    }
}
